package edu.ucdavis.gwt.gis.client.query;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import edu.ucdavis.cstars.client.MapWidget;
import edu.ucdavis.cstars.client.event.MapPanEndHandler;
import edu.ucdavis.cstars.client.event.MapZoomEndHandler;
import edu.ucdavis.cstars.client.geometry.Extent;
import edu.ucdavis.cstars.client.geometry.Point;
import edu.ucdavis.gwt.gis.client.DataManager;
import edu.ucdavis.gwt.gis.client.GisClient;

public class NoResultsPopup extends PopupPanel {
	
	private Point p = null;
	private MapWidget map = null;
	private PointSelectPanel pointPanel = null;
	
	public NoResultsPopup(PointSelectPanel pp) {
		this.pointPanel = pp;
		VerticalPanel vp = new VerticalPanel();
		vp.setSpacing(5);
		vp.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		vp.add(new HTML("Your query had 0 results returned."));
		
		Button b = new Button("Close");
		b.addClickHandler(new ClickHandler(){
			@Override
			public void onClick(ClickEvent event) {
				hide();
				pointPanel.hide();
			}
		});
		vp.add(b);
		
		setWidget(vp);
		setAnimationEnabled(true);
	}
	
	public void setMap(MapWidget map) {
		this.map = map;
		map.addPanEndHandler(new MapPanEndHandler() {
			@Override
			public void onMapPanEnd(Extent extent, Point endPoint) {
				if( isAttached() ) updatePosition();
			}
		});
		map.addZoomEndHandler(new MapZoomEndHandler() {
			@Override
			public void onZoomEnd(Extent extent, float zoomFactor,
					Point anchor, int level) {
				if( isAttached() ) updatePosition();
			}
		});
	}
	
	private void updatePosition() {
		Point sp = map.toScreen(p);
		GisClient client = DataManager.INSTANCE.getClient();
		setPopupPosition(client.getLeft()+(int) sp.getX(), client.getTop()+(int) sp.getY());
	}

	public void show(Point p) {
		this.p = p;
		hideTimer.cancel();
		setStyleName("NoResultsPopup");
		
		updatePosition();
		
		show();
		hideTimer.schedule(5000);
	}
	
	private Timer hideTimer = new Timer() {
		@Override
		public void run() {
			hide();
			pointPanel.hide();
		}
	};

}
